﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ueEngine.Framework.Exception;
using ueEngine.Framework.Common;
using ueEngine.Biz.Core.ExServer.WorkPool.WorkHandle.Email;
using ueEngine.Biz.Core.ExServer.WorkPool;
using ueEngine.Biz.Inf.LogicEntity;
using ueEngine.Framework.Caching;
using System.Configuration;

namespace ueEngine.Biz.Core.AppService.Member
{
    public class UserService 
    { 
        private string userName = string.Empty;
        public UserService(string username)
        {
            this.userName = username;
        }
        public MemberModel GetUser()
        {
            if (!String.IsNullOrEmpty(userName))
            {
                var item = ueCache.GetCache<MemberModel>("GetUser:" + userName);
                if (item == null)
                {
                    var user = new MemberModel().Element(c => c.UserName == userName);
                    return ueCache.Add<MemberModel>("GetUser:" + userName, user, CacheExpireStrategy.Sliding, new TimeSpan(0, 30, 0));
                }
                else
                {
                    return item;
                }
            }
            return null;
        }
        //public void RemoveCacheOfUser()
        //{
        //    if (!String.IsNullOrEmpty(userName))
        //    {
        //        ueCache.RemoveCache("GetUser:" + userName);
        //    }
        //}
        #region Account
        /// <summary>
        /// 新用户注册
        /// </summary>
        /// <param name="password">密码，使用AES进行加密</param>
        /// <param name="confirm">确认密码</param>
        /// <param name="IsCop">是否是商家</param>
        /// <returns>-1:用户名重复 0：失败 1：成功</returns>
        public MemberModel Register(string password, string confirm, bool IsCop,string qq="", string location = "", Collage collage =  Collage.Default)
        {
            if (CheckUserName() == 1)
            {
                return null;
            }
            if (String.IsNullOrEmpty(password) || password != confirm)
            {
                return null;
            }
            var item = new MemberModel()
            {
                UserName = this.userName,
                IsActivate = false,
                NickName = userName.Remove(this.userName.IndexOf('@')),
                Password = ueEngine.Framework.Common.AesAlgorithm.Encrypt(password),
                Token = ueEngine.Framework.Common.HashAlgorithm.Encrypt(Guid.NewGuid().ToString(), ueEngine.Framework.Common.EncryptMode.sha1),
                TokenDate = DateTime.Now,
                Role = IsCop ? MemberStatus.Firm : MemberStatus.Seeker,
                Sex = Gender.Male,
                RegisterDate = DateTime.Now,
                QQ = qq,
                Collage = collage
            };
            if (!String.IsNullOrEmpty(location))
            {
                item.Location = location;
            }
            if (item.PostAdd() != null)
            {
                WorkPool.Append<AccountEmail>(IsCop ? WorkType.email_for_register_b : WorkType.email_for_register_c, new AccountEmail()
                {
                    Recipient = this.userName,
                    Token = BuildFixToken(this.userName, item.Token, item.TokenDate),
                    TokenDate = item.TokenDate
                });

                WorkPool.Append<AdvertisementEmail>(WorkType.email_for_advertisement,
                   new AdvertisementEmail()
                   {
                       DisplayName = "要兼职",
                       Title = "有新人注册",
                       Html = String.Format("<b>重庆大学生兼职网管理员您好</b><div>于:{0}，有会员：{1}注册了{2}，特此通知，如有疑问请即刻查询。</div><div>谢谢</div>",
                        DateTime.Now.ToString(),
                        userName,
                        IsCop?"企业会员":"普通会员"),
                       Recipient = ConfigurationManager.AppSettings["adminnotice"]
                   }, null);
                return item;
            }
            return null;
        }
        public int ReSendEmail()
        {
            var user = GetUser();
            if (user != null)
            {
                var item = ModifyToken(user);
                WorkPool.Append<AccountEmail>(user.Role == MemberStatus.Firm ? WorkType.email_for_register_b : WorkType.email_for_register_c, new AccountEmail()
                {
                    Recipient = this.userName,
                    Token = BuildFixToken(this.userName, item.Token, item.TokenDate),//user.Token,
                    TokenDate = user.TokenDate
                });
                return 1;
            }
            return 0;
        }
        /// <summary>
        /// 修改Token
        /// </summary>
        /// <param name="tokenDate"></param>
        /// <param name="userName"></param>
        /// <returns>返回token</returns>
        private MemberModel ModifyToken(MemberModel model)
        {
            model.TokenDate = DateTime.Now;
            model.Token = HashAlgorithm.Encrypt(Guid.NewGuid().ToString(), EncryptMode.sha1);
            return model.PostModify();
        }
        /// <summary>
        /// 检测用户名是否已经存在
        /// </summary>
        /// <returns>0:不存在，可以使用 1：存在，不能使用</returns>
        public int CheckUserName()
        {
            return new MemberModel().IsExists(this.userName) ? 1 : 0;
        }
        /// <summary>
        /// 构建token值
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="token">Guid编码的token值</param>
        /// <param name="tokenDate">token的生成时间</param>
        /// <returns></returns>
        private string BuildFixToken(string userName, string token, DateTime tokenDate)
        {
            return EncodeByBase64.Encode(String.Format("{0}*{1}*{2}", userName, token, tokenDate.ToString()));
        }
        /// <summary>
        /// 激活用户
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public MemberModel Activation()
        {
            var user = GetUser();
            if (!user.IsActivate)
            {
                user.IsActivate = true;
                return user.PostModify();
            }
            return user;
        }
        /// <summary>
        /// 验证token
        /// </summary>
        /// <param name="token"></param>
        /// <param name="userName">token中包含的userName</param>
        /// <param name="tokenExpire">（单位：分钟，当值为0时不验证Token生成时间）Token的生成时间必须是当前时间的多少分钟之内</param>
        /// <returns></returns>
        public bool ValidToken(string token, ref string userName, int tokenExpire = 0)
        {
            string source = EncodeByBase64.Decode(token);
            string[] piece = source.Split('*');
            if (piece.Length < 3)
            {
                return false;
            }
            string _userName = piece[0];
            userName = _userName;
            this.userName = userName;

            try
            {
                var user = new MemberModel().Element(c => c.UserName == _userName);
                string Tokent = piece[1];
                string tokentDate = piece[2];
                if (user.Token == Tokent)
                {
                    if (tokenExpire > 0)
                    {
                        try
                        {
                            return user.TokenDate.AddMinutes(tokenExpire) >= DateTime.Parse(tokentDate);
                        }
                        catch (Exception)
                        {
                            return false;
                        }
                    }
                    return true;
                }
                return false;
            }
            catch (ContextException)
            {
                return false;
            }
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password">密码，需要使用AES加密进行比较</param>
        /// <returns>0：用户名或密码错误 1：成功</returns>
        public MemberModel Login(string password)
        {
            try
            {
                var user = GetUser();
                if (user!= null && user.Password == ueEngine.Framework.Common.AesAlgorithm.Encrypt(password))
                {
                    return user;
                }
            }
            catch (ContextException) { }
            return null;
        }
        /// <summary>
        /// 邮箱找回密码
        /// </summary>
        /// <returns></returns>
        public bool MailForResetPassword()
        {
            string newToken = HashAlgorithm.Encrypt(Guid.NewGuid().ToString(), EncryptMode.sha1);
            DateTime tokenDate = DateTime.Now;
            var dbMember = GetUser();
            dbMember.Token = newToken;
            dbMember.TokenDate = tokenDate;
            WorkPool.Append<AccountEmail>(WorkType.email_for_resetpassword, new AccountEmail()
            {
                Recipient = this.userName,
                Token = dbMember.Token,
                TokenDate = dbMember.TokenDate
            });
            //SendEmail(dbMember.Token, dbMember.TokenDate);
            return dbMember.PostModify() != null;
        }
        /// <summary>
        /// 改密码
        /// </summary>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public MemberModel ChangePassword(string oldPassword, string newPassword)
        {
            var dbMember = GetUser();
            if (dbMember.Password != AesAlgorithm.Encrypt(oldPassword))
            {
                return null;
            }
            dbMember.Password = AesAlgorithm.Encrypt(newPassword);
            if (dbMember.PostModify() != null)
            {
                return dbMember;
            }
            return null;
        }
        /// <summary>
        /// 改密码，不需验证旧密码
        /// </summary>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public MemberModel ChangePassword(string newPassword)
        {
            var dbMember = GetUser();
            dbMember.Password = AesAlgorithm.Encrypt(newPassword);
            if (dbMember.PostModify() != null)
            {
                return dbMember;
            }
            return null;
        }
        public MemberModel VerifyResetPasswordToken(string token)
        {
            var user = GetUser();
            if (user.Token == token && DateTime.Now <= user.TokenDate.AddHours(1))
            {
                ModifyToken(user); //修改token，使上封邮件失效
                return user;
            }
            return null;
        }
        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="nickName"></param>
        /// <param name="location"></param>
        /// <param name="sex"></param>
        /// <param name="realName"></param>
        /// <param name="phone"></param>
        /// <returns></returns>
        public MemberModel UpdateInfo(string nickName, string location, Gender sex, string realName, string phone,Collage collage)
        {
            var dbMember = GetUser();
            dbMember.NickName = nickName;
            dbMember.Location = location;
            dbMember.Sex = sex;
            dbMember.RealName = realName;
            dbMember.Phone = phone;
            dbMember.Collage = collage;
            if (dbMember.PostModify()!=null)
            {
                return dbMember;
            }
            return null;
        }
        /// <summary>
        /// 更新头像
        /// </summary>
        /// <param name="photo"></param>
        /// <returns></returns>
        public MemberModel UpdateImage(string photo)
        {
            var dbMember = GetUser();
            dbMember.Image = photo;
            if (dbMember.PostModify() != null)
            {
                return dbMember;
            }
            return null;
        }
        #endregion

    }
}
